﻿
namespace Anycmd.Host.AC.MessageHandlers
{
    using Anycmd.Rdb;
    using Bus;
    using Dapper;
    using Exceptions;
    using Identity;
    using Identity.Messages;
    using Logging;
    using System;
    using System.Data;
    using Util;

    public class AccountLogoutedEventHandler : IHandler<AccountLogoutedEvent>
    {
        private readonly IACDomain host;

        public AccountLogoutedEventHandler(IACDomain host)
        {
            this.host = host;
        }

        public void Handle(AccountLogoutedEvent message)
        {
            var visitingLogID = host.UserSession.GetData<Guid?>("UserContext_Current_VisitingLogID");
            if (visitingLogID.HasValue)
            {
                Guid dbID = new Guid("67E6CBF4-B481-4DDD-9FD9-1F0E06E9E1CB");
                RdbDescriptor db;
                if (!host.Rdbs.TryDb(dbID, out db))
                {
                    //throw new CoreException("意外的数据库标识" + dbID);
                    return;
                }
                using (var conn = db.GetConnection())
                {
                    if (conn.State != ConnectionState.Open)
                    {
                        conn.Open();
                    }
                    conn.Execute("update [VisitingLog] set StateCode=@StateCode,ReasonPhrase=@ReasonPhrase,Description=@Description,VisitedOn=@VisitedOn where Id=@Id", new
                    {
                        Id = visitingLogID.Value,
                        StateCode = (int)VisitState.LogOut,
                        ReasonPhrase = VisitState.LogOut.ToName(),
                        Description = "退出成功",
                        VisitedOn = SystemTime.Now()
                    });
                }
            }
        }
    }
}
